package com.yeswater.multithread.chapter1.test1_9;

import java.util.Iterator;
import java.util.Map;

/**
 * author : yeswater
 * date : 2023/10/18
 *
 * Thread.getAllStackTraces(); 返回所有活动线程堆栈信息的 map
 */

public class Test1 {

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        test1.a();
    }

    public void a() {
        b();
    }

    public void b() {
        c();
    }

    public void c() {
        d();
    }

    public void d() {
        e();
    }

    public void e() {
        Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
        if (map != null && map.size() != 0) {
            Iterator<Thread> keyIterator = map.keySet().iterator();
            while (keyIterator.hasNext()) {
                Thread eachThread = keyIterator.next();
                StackTraceElement[] arr = map.get(eachThread);
                System.out.println("------ 每个线程的基本信息");
                System.out.println(" 线程名称: " + eachThread.getName());
                System.out.println(" arr.length: " + arr.length);
                System.out.println(" 线程的状态: " + eachThread.getState());
                if (arr.length != 0) {
                    System.out.println(" 打印 StackTraceElement[] 数组具体信息: ");
                    for (int i = 0; i < arr.length; i++) {
                        StackTraceElement eachElement = arr[i];
                        System.out.println("    " + eachElement.getClassName() +
                                "  " + eachElement.getMethodName() +
                                "  " + eachElement.getMethodName() +
                                "  " + eachElement.getFileName() +
                                "  " + eachElement.getLineNumber());
                    }
                } else {
                    System.out.println("  没有 StackTraceElement[] 信息,因为线程 " +
                            eachThread.getName() + " 中的 StackTraceElement[].length==0");
                }
            }
        }
    }
}
